const jwt = require('jsonwebtoken')
const Controller = require('./base_controller')

class LoginController extends Controller {
  async index(ctx) {
    let maxAge = 12 * 60 * 60 //秒
    let { redisKey } = ctx.app.config
    let { userName, passWord } = ctx.query

    if (userName && passWord) {
      let res = await ctx.service.loginService.login(
        { userName, passWord }
      )
      if (res.rows && res.rows.length) {
        let { account_name, access_token } = res.rows
        let token = jwt.sign({
          account_name,
          access_token,
        }, this.config.keys, {
          expiresIn: '12h'
        })

        ctx.cookies.set('token', token, {
          maxAge: maxAge * 1000,
          httpOnly: false,
          overwrite: false,
          signed: false
        })

        this.success({
          data: { token }
        })
        redisKey += token.slice(-43)
        //写入redis
        await this.app.redis.set(redisKey, token, 'EX', maxAge)
      } else {
        this.error({
          msg: '用户名或密码错误！'
        })
      }
    } else {
      this.error({
        msg: '请输入正确的用户名或密码！'
      })
    }
  }
}

module.exports = LoginController